import { queryPageDataReq, toggleStateReq } from "./services";
import { namespace } from "./configFile";
import { message } from "antd";
import { queryUserInfoReq } from "@/services/global";

const groupByGroupId = (arrayOfObjects) => {
  const groupedByGroupId = { ...arrayOfObjects };

  // arrayOfObjects.forEach(item => {
  //   const groupId = item.groupName;
  //   if (!groupedByGroupId[groupId]) {
  //     groupedByGroupId[groupId] = [];
  //   }
  //   groupedByGroupId[groupId].push(item);
  // });
  console.log("groupedByGroupId", groupedByGroupId);
  const result = Object.keys(groupedByGroupId).map((groupId) => ({
    title: groupId,
    list: groupedByGroupId[groupId],
  }));
  return result;
};

export default {
  namespace,
  state: {
    init: false,
    wechatArr: [],
    data: {},
  },
  effects: {
    *pageInit({ params }, { call, put }) {
      const res = yield call(queryUserInfoReq);
      if (res && res.user && res.user.tenantId) {
        const wechatArr = yield call(queryPageDataReq, {
          ...params,
          tenantId: res.user.tenantId,
        });
        if (wechatArr) {
          yield put({
            type: "save",
            payload: {
              wechatArr: groupByGroupId(wechatArr),
              tenantId: res.user.tenantId,
            },
          });
        }
      }
    },
    *toggleState({ params, callback }, { call }) {
      let res = yield call(toggleStateReq, params);
      console.log(res);
      if (res?.code === 200) {
        message.success("操作成功");
        callback && callback();
      } else {
        message.error(res.msg);
      }
    },
  },
  reducers: {
    save(state: any, { payload }: any) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
